package self.Lunastic.HexaSweeper.Base;

import java.util.*;

/**
 * 循环更新对象
 */
public class UpdateLoop extends TimerTask {
    // 更新任务
    private final Runnable _update;
    // 更新间隔
    private final long _interval;

    private final Timer _timer;

    private boolean _running = false;
    public boolean isRunning(){return this._running;}

    /**
     * 自动更新
     * @param update 更新方法
     * @param interval 更新间隔
     */
    public UpdateLoop(Runnable update, long interval){
        this._update = update;
        this._interval = interval;
        this._timer = new Timer();
    }
    public void set(){
        this._timer.scheduleAtFixedRate(this, 0, this._interval);
    }

    public void start() {
        if(!isRunning()) {
            this._update.run();
            this._running = true;
        }
    }
    public void stop(){
        this._timer.cancel();
        this._running = false;
    }
    public void end(){
        if (this._running) this._timer.cancel();
        this._timer.purge();
        this._running = false;
    }

    @Override
    public void run() { this._update.run(); }
}
